package com.hontech.bvapp2.store

class Config (val name: String, val value: Int) {

    companion object {
        private const val TB_NAME = "tb_config"
        private const val CREATE_SQL = "CREATE TABLE IF NOT EXISTS $TB_NAME (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name TEXT NOT NULL, " +
                "value INTEGER NOT NULL, " +
                "UNIQUE (name) " +
                ")"

        suspend fun init() = Store.run { db ->
            db.execSQL(CREATE_SQL)
        }

        suspend fun set(name: String, value: Int) = Store.run { db ->
            db.beginTransaction()
            try {
                val cursor = db.rawQuery("SELECT id FROM $TB_NAME WHERE name = ? LIMIT 1", arrayOf(name))
                val exists = cursor.use {
                    cursor.moveToNext()
                }
                if (exists) {
                    db.execSQL("UPDATE $TB_NAME SET value = ? WHERE name = ?", arrayOf(value, name))
                } else {
                    db.execSQL("INSERT INTO $TB_NAME (name, value) VALUES (?, ?)", arrayOf(name, value))
                }
                db.setTransactionSuccessful()
            } finally {
                db.endTransaction()
            }
        }

        suspend fun get(name: String) = Store.run { db ->
            val cursor = db.rawQuery("SELECT value FROM $TB_NAME WHERE name = ? LIMIT 1", arrayOf(name))
            val value = cursor.use {
                if (!cursor.moveToNext()) {
                    throw IllegalStateException("无法获取:$name")
                }
                cursor.getInt(0)
            }
            value
        }

        suspend fun getWithDefault(name: String, default: Int): Int {
            try {
                return get(name)
            } catch (e: IllegalStateException) {
                e.printStackTrace()
                return default
            }
        }
    }
}